package com.itsu.spbspider.component.task;

import com.itsu.spbspider.entity.Crawler;
import com.itsu.spbspider.entity.News;
import com.itsu.spbspider.mapper.JobMapper;
import com.itsu.spbspider.service.impl.BaiduNewsCrawlerDB;
import com.itsu.spbspider.service.impl.BaiduNewsOrmData;
import com.itsu.spbspider.service.impl.BaiduNewsParser;
import com.itsu.spbspider.util.MybatisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Slf4j
public class BaiduNewsCrawlerTask implements Job {

    BaiduNewsCrawlerDB baiduNewsCrawlerDB = new BaiduNewsCrawlerDB();

    BaiduNewsParser baiduNewsParser = new BaiduNewsParser();

    BaiduNewsOrmData baiduNewsOrmData = new BaiduNewsOrmData();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        Crawler crawler = (Crawler) jobDataMap.get("crawler");
        com.itsu.spbspider.entity.Job job = (com.itsu.spbspider.entity.Job) jobDataMap.get("job");
        try {
            String content = baiduNewsCrawlerDB.crawlerData(crawler);
            List<News> list = baiduNewsParser.parseToObj(content);
            list.stream().forEach(x ->{
                x.setJobId(job.getId());
            });
            baiduNewsOrmData.writeDataToDbTask(list);
            job.setSuccessCount(job.getSuccessCount() + 1);
        } catch (Exception e) {
            log.error("error in job " + this.getClass().getName(), e);
            if (job.getErrorCount() > job.getRetry()) {
                SqlSession sqlSession = null;
                job.setStatus("N");
                job.setHeath("出现异常");
                job.setLastErrorTime(new Date());
                try {
                    sqlSession = MybatisUtil.getSqlSession();
                    JobMapper mapper = sqlSession.getMapper(JobMapper.class);
                    mapper.updateJob(job);
                    sqlSession.commit();
                } catch (Exception ex) {
                    sqlSession.rollback();
                } finally {
                    if (sqlSession != null)
                        sqlSession.close();
                }
                JobExecutionException e2 = new JobExecutionException(e);
                // Quartz将自动取消与此作业关联的所有触发器的调度，这样它就不会再次运行
                e2.setUnscheduleAllTriggers(true);
                throw e2;
            }
            job.setErrorCount(job.getErrorCount() + 1);

        } finally {
            SqlSession sqlSession = null;
            try {
                sqlSession = MybatisUtil.getSqlSession();
                JobMapper mapper = sqlSession.getMapper(JobMapper.class);
                job.setLastExcuteTime(new Date());
                mapper.updateJob(job);
                sqlSession.commit();
            } catch (Exception e) {
                e.printStackTrace();
                sqlSession.rollback();
            } finally {
                if (sqlSession != null)
                    sqlSession.close();
            }

        }
    }

}
